<?php


namespace app\system\controller;


use think\facade\View;
use think\facade\Db;

class Upgrade
{


    public function systemInfo()
    {
        $data["domain"] = request()->host();
        $data["version"] = SYSTEM_VERSION;

        $cloud = curlData("https://www.tn721.cn/admin/cloud/authInfo", $data, "POST");
        $cloudStatus = 1;
        if ($cloud == null) {
            $cloudStatus = 0;
        }

        if (count($cloud["keys"]) > 0) {
            $upgrate = 1;
        } else {
            $upgrate = 0;
        }

        View::assign("version", SYSTEM_VERSION);
        View::assign("cloudStatus", $cloudStatus);
        View::assign("domainStatus", $cloud["status"]);
        View::assign("upgrate", $upgrate);
        return View::fetch();
    }

    public function systemInstall()
    {
        $data["version"] = SYSTEM_VERSION;

        $url = "https://cloud.ymeoo.cn/api/system/upgroupVersions";
        $versionList = httpRequest($url, $data, "POST");

        if (count($versionList) > 0) {
            foreach ($versionList as $item) {

                //升级文件下载
                $saveFile = './update/' . time() . '.zip';
                $result = Http::down("http://cloud.ymeoo.cn/package/" .$item["package"] .".zip", $saveFile);

                if (!$result) {
                    return error("更新补丁下载失败");
                }

                $PclZip = new PclZip();
                $PclZip->PclZip($saveFile);

                $decomPath = './update/';

                if (!$PclZip->extract(PCLZIP_OPT_PATH, $decomPath, PCLZIP_OPT_REPLACE_NEWER)) {
                    return error("文件解压失败");
                }

                // 更新升级文件
                Dir::copyDir($decomPath . '/' . $item["package"], root_path());

                // 导入SQL
                $sqlFile = realpath($decomPath . '/' . $item["package"] . '/data/database.sql');
                if (is_file($sqlFile)) {
                    $sql = file_get_contents($sqlFile);
                    $sqlList = parse_sql($sql, 0, ['tn' => config('database.connections.mysql.prefix')]);
                    if ($sqlList) {
                        $sqlList = array_filter($sqlList);
                        foreach ($sqlList as $v) {
                            try {
                                Db::execute($v);
                            } catch (\Exception $e) {
                                return false;
                            }
                        }
                    }
                }

                //删除更新补丁目录和文件
                Dir::delDir('./update');
            }
            return notice("版本升级成功");
        } else {
            return notice("已是最新版本");
        }
    }
}